/*
 * UIJPGImage.cpp
 */

#include "UIJPGImage.h"
#include <iostream>
#include <SDL/SDL_image.h>

UIJPGImage::UIJPGImage(float x, float y, float width, float height,
    std::string file) {
  _xpos = x;
  _ypos = y;
  _depth = 0.;
  _width = width;
  _height = height;
  _file = file;
  _tex = 0;
  initSDLImageJPGSupport();
  if (!load(file)) {
    std::cout << "Cannot load JPG image file as an OpenGL Texture : " << file
        << std::endl;
  }
}

UIJPGImage::~UIJPGImage() {
  quitSDLImageJPGSupport();
  glDeleteTextures(1, &_tex);
}

bool UIJPGImage::load(std::string& file) {
  SDL_Surface* image = IMG_Load(file.c_str());
  if (!image) {
    printf("IMG_Load: %s\n", IMG_GetError());
    return false;
  } else {
    glGenTextures(1, &_tex);
    glBindTexture(GL_TEXTURE_2D, _tex);
    glColor3f(1.0,1.0,1.0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    SDL_LockSurface(image);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, image->w, image->h, 0, GL_RGB,
        GL_UNSIGNED_BYTE, image->pixels);
    SDL_UnlockSurface(image);

    SDL_FreeSurface(image);
    return true;
  }
}

void UIJPGImage::initSDLImageJPGSupport() {
  int flags = IMG_INIT_JPG;
  int initted = IMG_Init(flags);
  if ((initted & flags) != flags) {
    printf("IMG_Init: Failed to init required JPG support!\n");
    printf("IMG_Init: %s\n", IMG_GetError());
  }
}

void UIJPGImage::quitSDLImageJPGSupport() {
  IMG_Quit();
}
